﻿var CompanyValidationClientSideHide = false;
var PageNumber = 1;
var IsSearchView = false;
var IsDeleteView = false;
var CompanyIDView = 0;
var Phone800 = null;
var PhoneNumber = null;
var FaxNumber = null;
var CompanyAutoComElem = null;
var CompanyAutoComElemVal = null;
var CompanyTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("SetupCompany") != -1) {
        $.validator.addMethod("SetupCompanyRequireds", $.validator.methods.required, Messages["SetupCompanyRequireds"]);
        $.validator.addMethod("SetupCompanyMaxLength20", $.validator.methods.maxlength, Messages["SetupCompanyMaxLength20"]);
        $.validator.addMethod("SetupCompanyMaxLength50", $.validator.methods.maxlength, Messages["SetupCompanyMaxLength50"]);
        $.validator.addMethod("SetupCompanyMaxLength100", $.validator.methods.maxlength, Messages["SetupCompanyMaxLength100"]);
        $.validator.addClassRules({
            Required: {
                SetupCompanyRequireds: true,
            },
            MaxLength100: {
                SetupCompanyMaxLength100: 100,
            },
            MaxLength50: {
                SetupCompanyMaxLength50: 50,
            },
            MaxLength20: {
                SetupCompanyMaxLength20: 20,
            },
        });

        $('#LoadCompanyDetailsForm').validate();
        LoadCompanyGrid();
    }
});
$(document).on('change', '.CompanyDetailsElementChange', function () {
    if (!$('#CompanyDetailsSaveBtn').hasClass("disabled")) {
        $('#CompanyDetailsSaveBtn').addClass('BackColorRed');
    }
});
function DeleteCompany(CompanyID) {
    jConfirm('Are you sure you want to delete this Company?', 'Warning!', function (retVal) {
        if (retVal == true) {
            CompanyIDView = CompanyID;
            IsDeleteView = true;
            LoadCompanyGrid();
        }
    });
}

function ShowCompany(CompanyID)
{
    ShowCompanyDetails(CompanyID)
}
function ShowCompanyDetails(CompanyID) {
    $.ajax({
        url: urls["SetupLoadCompanyDetails"],
        data: { 'CompanyID': CompanyID },
        type: 'GET',
        success: function (data) {
            $("#CompaniesDetailsDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            IsDeleteView = false;
            ShowCompanyDetailPopUp("CompaniesDetailsDiv");
        }
    });
}
$(document).on('click', '#CompanyMoreBtn', function () {
    PageNumber = PageNumber + 1;
    IsDeleteView = false;
    LoadCompanyGrid();
});
$(document).on('click', '#CompanySearchBtn', function () {
    IsSearchView = true;
    IsDeleteView = false;
    LoadCompanyGrid();
});
function ShowCompanyDetailPopUp(PopUpDiv) {
    $.colorbox({
        width: "1200px",
        height: "700px",
        inline: true,
        href: "#"+PopUpDiv,
        onComplete: function () {
            Phone800 = $("#Phone800").val();
            PhoneNumber = $("#PhoneNumber").val();
            FaxNumber = $("#FaxNumber").val();
            $(".phoneUS").mask("+1 (###) ###-####");
            $(".PostalCode").mask("#####-####");
            $("#" + PopUpDiv).show(); 
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
$(document).on('click', '#CompanyDetailsSaveBtn', function () {
    var $form = $('#LoadCompanyDetailsForm');
    if ($form.valid()) {
        CompanyValidationClientSideHide = false;
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=x-user-defined');
            },
            success: function (data) {
                if (data.indexOf("Error") != -1)
                    jAlert(data, "Error");
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                if ($("#CompanyID").val() == 0) {
                    $('#CompanyDetailsSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    $('#cboxClose').click();
                    LoadCompanyGrid();
                }
                else {
                    $('#CompanyDetailsSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    ShowCompanyDetails($("#CompanyID").val())
                }
                IsDeleteView = false;
            }
        });
    }
    else
        CompanyValidationClientSideHide = true;
});
function LoadCompanyGrid()
{
    var SetupCompaniesGridViewModel = {
        CompanyNameText: $("#CompanyNameText").val(),
        CitySearchText: $("#CitySearchText").val(),
        CompanyCodeText: $("#CompanyCodeText").val(),
        PageNum: parseInt(PageNumber),
        IsSearch: IsSearchView,
        IsDelete: IsDeleteView,
        CompanyID: parseInt(CompanyIDView),
        IsActiveSearch: $("#IsActiveSearch").val(),
    };
    
    var DTO = JSON.stringify(SetupCompaniesGridViewModel);
    $.ajax({
        url: urls["SetupLoadCompaniesGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#SetupCompanyGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {

        }
    });
}
$(document).on('change', '.StateDrop', function () {
    var StateID = $(this).val();
    $.ajax({
        url: urls["SetupGetCityByCountryID"],
        data: { CountryID: 0, StateID: StateID },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "<option value='0'>Select</option>";
            for (var x = 0; x < data.length; x++) {
                markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
            }
            $("Select.CityDrop").html(markup);
        },
        error: function (reponse) {
            jAlert(reponse, "Error");
        },
        complete: function () {
            if (StateID === "" || StateID === "0") {
                $("#CityDiv").hide();
                $("#CityDivChange").show();
            }
            else {
                $("#CityDiv").show();
                $("#CityDivChange").hide();
            }
        }
    });
});
$(document).on('change', '#Phone800', function () {
    Phone800 = $(this).val();
});
$(document).on('change', '#PhoneNumber', function () {
    PhoneNumber = $(this).val();
});
$(document).on('change', '#FaxNumber', function () {
    FaxNumber = $(this).val();
});
$(document).on('change', '#PhoneNumberUnformatted', function () {
    if ($("#PhoneNumberUnformatted").prop('checked') == true) {
        $(".phoneUS").unmask();

        $("#Phone800").addClass("number");
        $("#PhoneNumber").addClass("number");
        $("#FaxNumber").addClass("number");
        $(".number").maskMoney({ prefix: '', allowNegative: false, thousands: '', decimal: '', affixesStay: false, precision: 0 });

        $("#Phone800").val(Phone800);
        $("#PhoneNumber").val(PhoneNumber);
        $("#FaxNumber").val(FaxNumber);
    }
    else {
        $(".number").unmask();
        $("#Phone800").removeClass("number");
        $("#PhoneNumber").removeClass("number");
        $("#FaxNumber").removeClass("number");
        $(".phoneUS").mask("+1 (###) ###-####");
    }
});
// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (CompanyTimerId == null) {
        CompanyAutoComElem = $(this).attr('id');
        CompanyAutoComElemVal = $("#" + CompanyAutoComElem).val();
        CompanyTimerId = setInterval(function () {

            var keyword = $("#" + CompanyAutoComElem).val();
            if (keyword == CompanyAutoComElemVal) {
                var PropName = "";
                if (CompanyAutoComElem.indexOf("CompanyCodeText") != -1)
                    PropName = "CompanyCodeText";
                if (CompanyAutoComElem.indexOf("CompanyNameText") != -1)
                    PropName = "CompanyNameText";

                var position = $("#" + CompanyAutoComElem).offset();
                position.top = position.top + $("#" + CompanyAutoComElem).height() + 5;
                $.ajax({
                    url: urls["SetupAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + CompanyAutoComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(CompanyTimerId);
                        CompanyTimerId = null;
                    }
                });
            }
            else
                CompanyAutoComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + CompanyAutoComElem).val(val);
    if (CompanyAutoComElem.indexOf("CompanyCodeText") != -1)
        $("#" + CompanyAutoComElem).next().val(key);
    if (CompanyAutoComElem.indexOf("CompanyNameText") != -1)
        $("#" + CompanyAutoComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}

var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#CompanyDetailsSaveBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#LoadCompanyDetailsForm").empty();
                LoadCompanyGrid();
                originalClose();
            }
        });
    }
    else {
        $("#LoadBankDetailsForm").empty();
        LoadCompanyGrid();
        originalClose();
    }
};
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (CompanyValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});